package in.muton.edushare.panels.upload;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.panels.upload.exceptions.FileProcessingException;
import in.muton.edushare.panels.upload.exceptions.InvalidUploadFileException;
import in.muton.wicket.extensions.upload.UploadProcessWebRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.MultiFileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.util.upload.FileUploadException;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.constants.ConfigPropertyName;
import com.edushare.common.global.SystemGlobals;
import com.edushare.common.vo.FileDirectories;
import com.edushare.common.vo.FilesUploaded;

public class MultipleFileUploadPanel extends Panel {

	private static final long serialVersionUID = -3426004052869428515L;
	private static Log log = LogFactory.getLog(MultipleFileUploadPanel.class);
	private final Collection<FileUpload> uploads = new ArrayList<FileUpload>();
	
	public MultipleFileUploadPanel(String id, IModel<FileDirectories> model) {
		super(id, model);
		
		
		add(new FeedbackPanel("feedback"));
		
		MultiFileUploadField mfufi = new MultiFileUploadField(
				"fileInput", 
				new PropertyModel<Collection<FileUpload>>(this, "uploads"), 
				ApplicationConstants.MAX_FILES_UPLOADABLE);
		
		Form<Void> uf = new Form<Void>("uform"){

			private static final long serialVersionUID = -3013767689313690001L;

			@Override
			protected void onSubmit() {
				ArrayList<FilesUploaded> successfulUploads = new ArrayList<FilesUploaded>();
				for(FileUpload fu: uploads){
					if(fu!=null){
						log.debug("Uploaded File Name: "+ fu.getClientFileName()+", "+ fu.getSize());
						log.debug("File Upload: "+fu);
						Uploader uploader = new Uploader(
												fu, 
												(FileDirectories)MultipleFileUploadPanel.this.getDefaultModelObject());
						
						FilesUploaded uploadedFile = null;
						try {
							uploadedFile = uploader.startUploading();
						} catch (InvalidUploadFileException e) {
							warn("Invalid File.");
							e.printStackTrace();
						} catch (IOException e) {
							warn("Error during upload");
							e.printStackTrace();
						} catch (FileProcessingException e) {
							warn("Error in processing this file");
							e.printStackTrace();
						}
						successfulUploads.add(uploadedFile);
					}
				}
				
				postprocessingCleanup();
				EduShareSession.get().setFileUploadedInLastUpload(successfulUploads);
				EduShareSession.get().updateUploadedFileThisSession(successfulUploads.size());//uploads.size());
			}
			
			@Override
			protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
				log.debug("*** FILE UPLOAD EXCEPTION ***");
				warn("Max upload limit exceeded.");
				super.onFileUploadException(e, model);
			}
		};
		
		uf.setMultiPart(true);
		uf.setMaxSize(Bytes.kilobytes(
										Long.parseLong(
												SystemGlobals.getInstance()
												.getConfigProperty(ConfigPropertyName.UPLOAD_MAXSIZE_KB)
												)
												));
		add(uf);
		uf.add(mfufi);
		
//		
//		TODO: ProgressBar is not functioning properly for more than one files
//		uf.add(new UploadProcessProgressBar("progressBar", uf));
	}
	
	private void postprocessingCleanup(){
		log.debug("Clearing info");
		HttpServletRequest req = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest();
		UploadProcessWebRequest.clearUploadInfo(req);
	}

}
